/**
 * Project: common-util
 * Created: 2016年7月5日
 * Copyright ©2011 - 2016 gopay Information Technology Co., LTD All Rights Reserved
**/
package com.gopay.common.util.cbrmb;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * <P>
 * ClassName CbrmbJsonUtils
 * <P>
 * Description 重写的跨境人民币JSON工具类,将可检异常转为不可检异常,已方便框架处理.
 * 
 * @author junjie.ge
 * @date 2016年7月5日 下午2:42:49
 */

public abstract class CbrmbJsonUtils {
	
	private static void handleJsonException(Exception e) {
		throw new IllegalStateException(e);
	}
	/**
	 * 将Json转换为List
	 * 
	 * @param content
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> toList(String content) {
		if (StringUtils.isBlank(content)) {
			return null;
		}

		List<Map<String, Object>> model = new ArrayList<Map<String, Object>>();
		ObjectMapper mapper = new ObjectMapper();

		try {
			model = mapper.readValue(content, List.class);
		} catch (Exception e) {
			handleJsonException(e);
		}

		return model;
	}

	/**
	 * 将Json转换为Map
	 * 
	 * @param content
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> toMap(String content) {
		if (StringUtils.isBlank(content)) {
			return null;
		}

		Map<String, String> model = new HashMap<String, String>();
		ObjectMapper mapper = new ObjectMapper();

		try {
			model = mapper.readValue(content, Map.class);
		} catch (Exception e) {
			handleJsonException(e);
		}

		return model;
	}

	/**
	 * 将JSON串转为Map
	 * 
	 * @param json
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(String json) {
		if (StringUtils.isBlank(json)) {
			return null;
		}

		Map<String, Object> model = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();

		try {
			model = mapper.readValue(json, Map.class);
		} catch (Exception e) {
			handleJsonException(e);
		}
		return model;
	}

	/**
	 * 将对象解析为json串
	 * 
	 * @param obj
	 * @return
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static String toJson(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json = mapper.writeValueAsString(obj);
		} catch (Exception e) {
			handleJsonException(e);
		}
		return json;
	}
}
